from base.web import SHandler, get_files, BaseHandler

domin = 'http://p92yjj2v1.bkt.clouddn.com/'
class create_product(SHandler):
    def post(self):
        #(name shortname price types remark) should be post. ( isdel isrecommend id ) will be create auto.
        filter = ['name', 'shortname', 'price', 'contentid', 'remark']
        params = []  #字段容器
        filesList = []
        for key in filter:
            value = self.get_argument(key, '')
            if key != 'contentid':
                value = '\'' + value + '\''
            params.append(value)
        if self.request.files:
            filesList = get_files(self.request.files)['data']
        params.append('\'' + ','.join(filesList) + '\'')
        insert_data = dict(
            keys = ','.join(filter),
            values = ','.join(params)
        )
        if self.insert_sql('insert into pj_product({keys},img) values({values});'.format(**insert_data)):
            res = self.res_success('insert')
        else:
            res = self.res_error('insert')
        self.write(res)

class modify_product(SHandler):
    def post(self):
        updateList = ['name', 'shortname', 'contentid', 'price', 'remark']
        params = []
        filesList = []
        savelist = []
        for key in updateList:
            value = self.get_argument(key, '')
            if value:
                if key != 'contentid':
                    value = key + '=' + '\'' + value + '\''
                else:
                    value = key + '=' + value
                params.append(value)
        if self.request.files:
            filesList = get_files(self.request.files)['data']
        if self.get_argument('img', ''):
            savelist = filesList + self.get_argument('img', '').split(',')
        else:
            savelist = filesList
        params.append('img=' + '\'' + ','.join(savelist) + '\'')
        if self.modify_sql('''update pj_product set {params} where id = {id};'''.format(params=','.join(params), id = int(self.get_argument('id', '')))):
            res = self.res_success('modify')
        else:
            res = self.res_success('modify')
        self.write(res)

class query_product(BaseHandler):
    def post(self):
        current_page = int(self.get_argument('current_page', 1))
        page_size = int(self.get_argument('page_size', 10))
        contentid = self.get_argument('contentid', 0) or 0
        if contentid == '0':
            contentid = int(contentid)
        name = self.get_argument('name', '')
        try:
            intname = int(name)
        except:
            intname = 0
        total = self.query_sql('''select isdel, count(*) as total 
            from pj_product where isdel = 0 group by isdel''')[0]['total']
        try:
            data = self.query_sql('''select * from pj_product where 
                ((name like \'%{name}%\' or shortname like \'%{name}%\' or id = {intname}))
                and (isdel = 0 and contentid {q} ({contentid})) limit {start}, {end};
                '''.format(
                    name = name, 
                    start = (current_page - 1) * page_size, 
                    end = current_page * page_size, 
                    contentid = contentid, 
                    intname = intname,
                    q = ('in' if contentid else 'not in')))
            for i in data:
                i['ctime'] = str(i['ctime'])
            res = self.res_success('query', data, dict(total = total, domin = domin))
        except:
            res = self.res_error('query')
        self.write(res)

class del_product(SHandler):
    def post(self):
        if self.modify_sql('update pj_product set isdel = {isdel} where id = {id};'.format(
                isdel = int(self.get_argument('isdel', 0)),
                id = int(self.get_argument('id', 0))
            )):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)
class set_recommend(SHandler):
    def post(self):
        if self.modify_sql('update pj_product set isrecommend = {isrecommend} where id = {id};'.format(
                isrecommend = int(self.get_argument('isrecommend', 0)),
                id = int(self.get_argument('id', 0))
            )):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class product_detail(BaseHandler):
    def post(self):
        try:
            product = self.query_sql('select * from pj_product where id = {id}'.format(id = int(self.get_argument('id', ''))))[0]
            product['ctime'] = str(product['ctime'])
            res = self.res_success('query', object={'product': product, 'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)
product_url = [
    (r'/api/product/create_product', create_product),
    (r'/api/product/modify_product', modify_product),
    (r'/api/product/query_product', query_product),
    (r'/api/product/del_product', del_product),
    (r'/api/product/set_recommend', set_recommend),
    (r'/api/product/product_detail', product_detail)
]